import { createRouter, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import NotePage from '../views/NotPage/NotePage.vue'

const routes = [
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  },
  //  登录页
  {
    path: '/login',
    name: 'login',
    component: ()=>import('../views/Login.vue')
  },
  // 首页
  { 
    path:'/',
    name:'主页',
    // 这里是一级路由显示的页面
    component:()=>import('../views/layout/index.vue'),
    redirect:'/index',
    // 这里是二级路由显示的页面
    children:[
      {
        path:'/index',
        name:'首页',
        component:()=>import('../views/index/index.vue')
      },
      {
        path:'/sys/user',
        name:'用户管理',
        component:()=>import('../views/sys/user/index.vue')
      },
      {
        path:'/sys/role',
        name:'角色管理',
        component:()=>import('../views/sys/role/index.vue')
      },
      {
        path:'/sys/menu',
        name:'菜单管理',
        component:()=>import('../views/sys/menu/index.vue')
      },
      {
        path:'/bsns/Department',
        name:'部门管理',
        component:()=>import('../views/bsns/Department.vue')
      },
      {
        path:'/bsns/Post',
        name:'岗位管理',
        component:()=>import('../views/bsns/Post.vue')
      },
      {
        path:'/userCenter',
        name:'个人中心',
        component:()=>import('../views/userCenter/index.vue')
      }
    ],
    meta:{islogin:true}
  },
  // 错误页面跳转
  // 路径错误组件
  {
    path: '/:pathMatch(.*)',
    component: NotePage,
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})


// 全局前置路由守卫
router.beforeEach((to,from)=>{
  // to是即将离开的路由,from是将要进入的路由
  // 注意to和from里面存储了页面的数据,如meta里面的数据
  // 获取页面存储的token
  const token = sessionStorage.getItem('token')
  // 能进入说明没有登录
  if(!token){
      if(to.meta.islogin){
          // 进行重定向,到登录页,将跳转前的页面数据传输过去
          return {path:'/login', query:{path:to.path}}
      }
  }
})

export default router
